package com.yueke.gemini.utils;

import org.jdom.JDOMException;

import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by paco on 2016/7/11.
 */
public final class StringUtil {
    public static String valueOf(Object o){
        if(o==null){return "";}
        String ov=o.toString().trim();
        if("null".equalsIgnoreCase(ov)){return "";}
        return ov;
    }

    public static boolean isNull(Object o){
        if(o==null){return true;}
        String to=valueOf(o);
        if(to.trim().isEmpty()||to.trim().equals("")){return true;}

        return false;
    }

    public static boolean isNotNull(Object o){
        return !isNull(o);
    }

    public static boolean isDigital(String o){
        Pattern pattern = Pattern.compile("\\s*\\d+\\s*$");
        Matcher isNum = pattern.matcher(o);
        if( isNum.matches() ){ return true;}
        return false;
    }

    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("\\s*-?[0-9]+(.[0-9]+)?\\s*$");
        Matcher isNum = pattern.matcher(str);
        if( isNum.matches() ){ return true;}
        return false;
    }

    public static String valueOf(Object o,String defaultvalue){
        String s=null;

        s=isNull(o)?defaultvalue:valueOf(o);

        return s;
    }

    public static boolean isFullDate(Object o){
        if(isNull(o)){return false;}
        String str=valueOf(o).trim();
        Pattern pattern = Pattern.compile("^(\\s*\\d{2}|\\d{4})(\\-|/)\\d{1,2}(\\-|/)\\d{1,2}\\s+\\d{1,2}(\\:|\\：)\\d{1,2}(\\:|\\：)\\d{1,2}\\s*$");
        Matcher isNum = pattern.matcher(str);
        if( isNum.matches() ){ return true;}
        return false;
    }

    public static boolean isDate(Object o){
        if(isNull(o)){return false;}
        String str=valueOf(o).trim();
        Pattern pattern = Pattern.compile("^(\\s*\\d{2}|\\d{4})(\\-|/)\\d{1,2}(\\-|/)\\d{1,2}\\s*$");
        Matcher isNum = pattern.matcher(str);
        if( isNum.matches() ){ return true;}
        return false;
    }

    public static String getXMLSql(String xml){
        String sql=null;
        if(StringUtil.isNull(xml)){return sql;}

        try {
            Map m=XMLUtil.doXMLParse(xml);
            sql=StringUtil.valueOf(m.get("sql"));
            sql=sql.replaceAll("&apos;","'");
        } catch (JDOMException e) {
            System.out.println("xml format error:"+xml);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sql;
    }
}
